package com.example.demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class Util {
	
	public static void sleepSeconds(int sec) {
		try {
			Thread.sleep(sec*1000);	
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 如果元素大小都相等,则丢弃后面的.
	 */
	public static <E extends Comparable<E>> List<E> getTopN(Collection<E> items, int n) {
		PriorityQueue<E> heap = new PriorityQueue<>(n);

		for (E item : items) {
			if (heap.size() < n) {
				heap.offer(item);
			} else if (item.compareTo(heap.peek()) > 0) {
				heap.poll();
				heap.offer(item);
			}
		}

		List<E> topN = new ArrayList<>(heap);
		Collections.sort(topN);
		return topN;
	}

	/**
	 * 解析正文中的段落,文本或图片
	 * 
	 * @param htmlContent
	 * @return
	 */
	public static List<Paragraph> parseParagraph(String htmlContent) {
		String tag = "window.__APOLLO_STATE__ =";
		int startIdx = htmlContent.indexOf(tag) + tag.length();
		String content = htmlContent.substring(startIdx);
		String json = content.substring(0, content.indexOf("</script>"));
		JSONObject pis = JSONUtil.parseObj(json);

		LinkedHashMap<String, JSONObject> imageMetadatas = new LinkedHashMap<>();
		LinkedHashMap<String, JSONObject> paragraphs = new LinkedHashMap<>();
		pis.forEach((k, v) -> {
			if (v instanceof JSONObject) {
				if (k.startsWith("Paragraph:")) {
					paragraphs.put(k, (JSONObject) v);
				} else if (k.startsWith("ImageMetadata:")) {
					imageMetadatas.put(k, (JSONObject) v);
				}
			}
		});

		List<Paragraph> ps = new LinkedList<>();
		paragraphs.forEach((k, v) -> {
			Paragraph p = new Paragraph();
			ps.add(p);
			p.setType((String) v.get("type"));
			if ("IMG".equals(v.get("type"))) {
				JSONObject metadata = (JSONObject) v.get("metadata");
				String imgId = metadata.get("__ref").toString();
//				JSONObject imgObj = imageMetadatas.get(imgId);
				p.setImgId(imgId.replace("ImageMetadata:", ""));
//				p.setImgUrl("https://miro.medium.com/v2/resize:fit:720/format:webp/"+imgId.replace("ImageMetadata:", ""));
//				p.setOriginalHeight((Integer) imgObj.get("originalHeight"));
//				p.setOriginalHeight((Integer) imgObj.get("originalHeight"));
			} else {
				p.setText((String) v.get("text"));
			}
		});

		return ps;
	}
}
